<template>
  <ProjectInfo
    ref="projectInfoRef"
    :needSignatureCheck="true"
    v-if="!tbflag"
    :projectId="`${route.query.projectId}`"
    :reportType="'MMK'"
    :sync="true"
    :upload="true"
    :sign="true"
    :uploadContent="'上传定性实验结果'"
    :syncContent="'从定性采样同步基础信息'"
    @on-sync-header="onSyncHeader"
    @signature="handleSignature"
  />
  <!--  @preview-file="onPreviewHeader"-->

  <ContentWrap>
    <!-- 数据为空时的提示 -->
    <div v-if="!hasData && !isInitializing" class="empty-data-tip">
      <el-empty description="暂无数据">
        <template #image>
          <el-icon size="60" color="#c0c4cc">
            <Document />
          </el-icon>
        </template>
        <template #description>
          <p style="margin: 10px 0; color: #909399;">暂无分析数据，请先点击上方"从定性采样同步基础信息"按钮同步数据</p>
        </template>
        <el-button type="primary" @click="onSyncHeader">同步数据</el-button>
      </el-empty>
    </div>

    <!-- 有数据时显示内容 -->
    <div v-else style="position: relative">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="二氧化硅含量" name="silica">
          <TestSiliconDioxide
            :key="'silica-' + syncVersion"
            ref="silicaAnalysisRef"
            :silica-item="silicaItem"
            :tbflag="tbflag"
            @change="(data) => handleAnalysisChange(data, 'silica')"
          />
        </el-tab-pane>
        <el-tab-pane v-if="volatileItem.length > 0" label="有机组分含量" name="volatile">
          <div
            v-for="(item) in volatileItem"
            :key="item.sampleNo + '-' + syncVersion"
            class="record-item"
          >
            <OrganicQualitativeResult
              ref="volatileAnalysisRef"
              :tbflag="tbflag"
              :volatile-item="item"
              @change="(data) => handleAnalysisChange(data, 'volatile')"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, ref, watch, computed } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { useRoute } from 'vue-router'
import TestSiliconDioxide from './TestSiliconDioxide.vue'
import OrganicQualitativeResult from './OrganicQualitativeResult.vue'
import { ProjectApi } from '@/api/dk/project'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'
defineOptions({ name: 'UnknownAnalysis' })
const props = defineProps({
  // 字符串类型的prop，带有默认值
  tbflag: {
    type: Boolean,
    default: false
  } ,
  projectId: Number
})
const route = useRoute()
const volatileItem = ref<any[]>([])
const projectInfoRef = ref()

const handleSignature = () => {
  // 先进行数据校验
  if (signatureCheck()) {
    // 校验通过，显示签名弹窗
    if (projectInfoRef.value) {
      projectInfoRef.value.showSignatureDialog()
    }
  }
  // 校验不通过时，不显示弹窗，错误信息已在 signatureCheck 中提示
}

// 校验签名前的数据完整性
const signatureCheck = (): boolean => {
  // 校验二氧化硅含量数据
  const silicaForm = silicaAnalysisRef.value?.form
  if (silicaForm?.table && Array.isArray(silicaForm.table) && silicaForm.table.length > 0) {
    const silicaError = validateSilicaTable(silicaForm.table)
    if (silicaError) {
      ElMessage.error(silicaError)
      activeTab.value = 'silica'
      return false
    }
  }

  // 校验有机组分含量数据
  const volatileRefs = Array.isArray(volatileAnalysisRef.value) ? volatileAnalysisRef.value : []
  for (let i = 0; i < volatileRefs.length; i++) {
    const volatileForm = volatileRefs[i]?.form
    if (volatileForm?.table && Array.isArray(volatileForm.table)) {
      const volatileError = validateVolatileTable(volatileForm.table, i + 1)
      if (volatileError) {
        ElMessage.error(volatileError)
        activeTab.value = 'volatile'
        return false
      }
    }
  }

  return true
}

// 校验二氧化硅表格数据
const validateSilicaTable = (table: any[]): string | null => {
  // 必须字段列表（排除只读的计算字段）
  const requiredFields = [
    { key: 'post', label: '代表/取样场所、岗位、地点' },
    { key: 'sampleNo', label: '样品编号' },
    { key: 'sampleMass', label: '样品质量G(g)' },
    { key: 'm3', label: 'm3(g)' },
    { key: 'm4', label: 'm4(g)' },
    { key: 'm5', label: 'm5(g)' },
    { key: 'm6', label: 'm6(g)' }
  ]

  for (let i = 0; i < table.length; i++) {
    const row = table[i]
    const rowIndex = i + 1

    for (const field of requiredFields) {
      const value = row[field.key]
      const isEmpty = value === undefined || value === null || value === '' || (typeof value === 'string' && value.trim() === '')
      
      if (isEmpty) {
        return `二氧化硅含量：第${rowIndex}行的"${field.label}"不能为空`
      }
    }
  }

  return null
}

// 校验有机组分表格数据
const validateVolatileTable = (table: any[], recordIndex: number): string | null => {
  // 必须字段列表
  const requiredFields = [
    { key: 'post', label: '代表/取样场所、岗位、地点' },
    { key: 'componentName', label: '检出的挥发性有机组分名称' },
    { key: 'casNo', label: 'CAS号' },
    { key: 'peakAreaPercentage', label: '峰面积百分比(%)' }
  ]

  for (let i = 0; i < table.length; i++) {
    const row = table[i]
    const rowIndex = i + 1

    for (const field of requiredFields) {
      const value = row[field.key]
      const isEmpty = value === undefined || value === null || value === '' || (typeof value === 'string' && value.trim() === '')
      
      if (isEmpty) {
        const recordLabel = recordIndex > 1 ? `第${recordIndex}个样品` : ''
        return `有机组分含量${recordLabel}：第${rowIndex}行的"${field.label}"不能为空`
      }
    }
  }

  return null
}

// 从sessionStorage读取保存的tab状态，如果没有则根据数据情况智能选择
const getInitialTab = () => {
  const savedTab = sessionStorage.getItem('UnknownAnalysisResult_activeTab')
  if (savedTab) {
    return savedTab
  }
  // 默认选择silica tab
  return 'silica'
}
const activeTab = ref(getInitialTab())

/** 同步：覆盖已有数据前二次确认 */
const onSyncHeader = async () => {
  try {
    await ElMessageBox.confirm('已有数据将被覆盖，确认是否同步？', '确认同步', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }

  isInitializing.value = true
  await getDefaultUnknownAnalysisResult()
  await nextTick()
  syncVersion.value++
  isInitializing.value = false
  // 数据与子组件渲染完成后再统一保存，避免读取到空数组
  handleAnalysisChange(undefined as any, 'volatile')
}

const volatileAnalysisRef = ref<any[]>([])
const silicaAnalysisRef = ref()
const silicaItem = ref()
const isInitializing = ref(false)
const syncVersion = ref(0)

// 计算是否有数据
const hasData = computed(() => {
  return volatileItem.value.length > 0 || (silicaItem.value && Object.keys(silicaItem.value).length > 0)
})

// 监听 tab 切换
watch(activeTab, (newVal) => {
  // 保存当前选中的tab到sessionStorage
  sessionStorage.setItem('UnknownAnalysisResult_activeTab', newVal)
}, { immediate: true })

// 处理子组件数据变化并保存
const handleAnalysisChange = (_data: any, _type: 'volatile' | 'silica') => {
  if (isInitializing.value) {
    return
  }

  // 直接保存，移除防抖定时器
  performSave()
}

// 执行保存操作
const performSave = () => {
  const volatileList = Array.isArray(volatileAnalysisRef.value)
    ? volatileAnalysisRef.value.map((comp: any) => comp?.form || {})
    : []
  const silicaData = silicaAnalysisRef.value?.form || {}
  const projectId = route.query.projectId

  const saveData = {
    volatile: { data: { table: volatileList } },
    silica: { data: silicaData },
    projectId: projectId
  }

  ProjectApi.updateUnknownAnalysisResult(saveData)
    .then(() => {
      ElMessage.success('已自动保存')
    })
    .catch((error) => {
      console.error('保存失败:', error)
      ElMessage.error('保存失败，请重试')
    })
}

// 默认表格数据
const defaultTableData = [
  { post: '', retentionTime: '', componentName: '苯', casNo: '71-43-2', peakAreaPercentage: '未检出', remark: '' },
  { post: '', retentionTime: '', componentName: '1,2-二氯乙烷', casNo: '107-06-2', peakAreaPercentage: '未检出', remark: '' },
  { post: '', retentionTime: '', componentName: '正己烷', casNo: '110-54-3', peakAreaPercentage: '未检出', remark: '' },
  { post: '', retentionTime: '', componentName: '三氯乙烯', casNo: '79-01-6', peakAreaPercentage: '未检出', remark: '' },
  { post: '', retentionTime: '', componentName: '丙酮', casNo: '67-64-1', peakAreaPercentage: '未检出', remark: '' }
]

// 将表格数据转换为组件期望的格式
const transformVolatileData = (tableData: any[]) => {
  const sortedData = [...tableData].sort((a, b) => (a.sampleNo || '').localeCompare(b.sampleNo || ''))

  return sortedData.map(item => {
    if (item.table && Array.isArray(item.table)) {
      return { ...item, projectId: route.query.projectId }
    }

    const post = Array.isArray(item.post) ? item.post.join(', ') : (item.post || '')
    const defaultTable = defaultTableData.map(row => ({ ...row, post }))

    return {
      projectId: route.query.projectId,
      taskNo: item.taskNo || '',
      detectionType: item.detectionType || '定期检测',
      sampleName: item.materialName || item.sampleName || '',
      sampleNo: item.sampleNo || '',
      detectionItem: item.detectionItem || '挥发有机组分定性及峰面积百分比测定',
      temperature: item.temperature || '26',
      humidity: item.humidity || '50',
      submissionDate: item.submissionDate || '',
      testDate: item.testDate || new Date().toISOString().split('T')[0],
      testStandard: item.testStandard || 'GDOHTQC 001-2020《化学品中挥发性有机组分定性分析和峰面积百分比测定顶空气相色谱-质谱法》',
      reportMethod: item.reportMethod || '有机挥发物成分按峰面积归一法计算各组分相对百分含量；有机挥发物的定性结果与标准谱库匹配度小于     %，为其他物质。',
      instrumentName: item.instrumentName || '气质联用仪',
      instrumentModel: item.instrumentModel || '7890B-5977B',
      instrumentSerial: item.instrumentSerial || 'HAYQ2053',
      instrumentInfo: item.instrumentInfo || '',
      columnName: item.columnName || 'HP-VOC',
      columnLength: item.columnLength || '60',
      innerDiameter: item.innerDiameter || '0.2',
      filmThickness: item.filmThickness || '1.12',
      columnTempProgram: item.columnTempProgram || '',
      vaporizationTemp: item.vaporizationTemp || '250',
      scanMode: item.scanMode || '全扫描',
      carrierGasFlow: item.carrierGasFlow || '1.0',
      scanRange: item.scanRange || '10-550',
      auxiliaryTemp: item.auxiliaryTemp || '250',
      solventDelay: item.solventDelay || '0',
      ionSourceTemp: item.ionSourceTemp || '230',
      splitRatio: item.splitRatio || '10:1',
      quadrupoleTemp: item.quadrupoleTemp || '150',
      injectionVolume: item.injectionVolume || '1.0',
      sampleTreatment: item.sampleTreatment || '称取5.0g样品于20mL顶空瓶中,于40℃电热恒温鼓风干燥箱中加热平衡30min。',
      qualitativeAnalysis: item.qualitativeAnalysis || '对检出组分的峰面积进行归一法计算,得到各组分的峰面积百分比。',
      totalVolatileOrganicPercentage: item.totalVolatileOrganicPercentage || '',
      inorganicPercentage: item.inorganicPercentage || '',
      table: item.table || defaultTable
    }
  })
}

// 获取数据并返显
const getDefaultUnknownAnalysisResult = async () => {
  const projectId = route.query.projectId
  if (!projectId) return

  const data = await ProjectApi.getDefaultUnknownAnalysisResult(Number(projectId))
  console.log('同步获取到的完整数据:', JSON.stringify(data, null, 2))

  const tableData = data?.volatile?.data?.table || []
  volatileItem.value = transformVolatileData(tableData)
  silicaItem.value = data?.silica?.data || {}

  console.log('同步设置后的 silicaItem.value:', JSON.stringify(silicaItem.value, null, 2))
  console.log('同步后 hasData 计算结果:', hasData.value)
}

const getUnknownAnalysisResult = async () => {
  console.log('开始获取数据...',props.projectId)
  let projectId: number | undefined
  if (route.query.projectId) {
    projectId = Number(route.query.projectId) // Convert string to number
  } else {
    projectId = props.projectId
  }

  const data = await ProjectApi.getUnknownAnalysisResult(Number(projectId))
  console.log('获取到的完整数据:', JSON.stringify(data, null, 2))

  const tableData = data?.volatile?.data?.table || []
  volatileItem.value = transformVolatileData(tableData)
  silicaItem.value = data?.silica?.data || {}

  console.log('设置后的 silicaItem.value:', JSON.stringify(silicaItem.value, null, 2))
  console.log('hasData 计算结果:', hasData.value)
}

// 页面加载时获取数据
onMounted(async () => {
  console.log('开始初始化数据111...',props.projectId)
  isInitializing.value = true
  await getUnknownAnalysisResult()
  await nextTick()
  isInitializing.value = false

  // 数据加载完成后，如果没有保存的tab状态，根据数据情况智能选择tab
  const savedTab = sessionStorage.getItem('UnknownAnalysisResult_activeTab')
  if (!savedTab) {
    // 如果有机组分有数据，优先显示有机组分tab
    if (volatileItem.value.length > 0) {
      activeTab.value = 'volatile'
    } else {
      // 否则显示二氧化硅tab
      activeTab.value = 'silica'
    }
  }

  console.log("tbflagtbflagtbflagtbflag:", route.query.tbflag)
})
</script>

<style lang="scss" scoped>
:deep(.el-tabs__header) {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px; /* 确保按钮有空间显示 */
}

:deep(.el-tabs__nav-wrap) {
  flex-grow: 1;
  display: flex;
  align-items: center;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  height: 40px;
  line-height: 40px;
}

.header-extra-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
  margin-left: 15px; /* 添加左侧间距 */
}

.empty-data-tip {
  padding: 40px 20px;
  text-align: center;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.empty-data-tip .el-empty {
  padding: 0;
}

.empty-data-tip .el-empty__description {
  margin-top: 16px;
}
</style>
